
/*******************************************
@description 打开窗口
@author  lixh@bingosoft.net
@example
打开窗口            ： jQuery.open( url , width , height , params ,callback ) ;
在打开窗口中获取参数 ： var args        = jQuery.dialogAraguments() ;
获取打开窗口中返回值 ： var returnValue = jQuery.dialogReturnValue() ;
******************************************/

var _dialogArguments = null;
var _dialogWin = null;
var _returnValue = null;
/**
* 
* @param {} url
* @param {} width
* @param {} height
* @param {} params  json对象  
* 		title:'' --dialog对应的title
* 		showType:'' 窗口打开类型（dialog:div层 ， open：window.open，model: '模态窗口'）
* @param {} callback
* @return {}
*/
jQuery.open = function (url, width, height, params, callback, fixParams) {
    url = jQuery.utils.parseUrl(url);

    // 加上时间戳
    var randomCode = new Date().valueOf();
    if (url.indexOf("?") >= 0) {
        url = url + "&" + randomCode;
    } else {
        url = url + "?" + randomCode;
    }

    callback = callback || function () { };
    var innerCallback = function () {
        callback(jQuery.dialogReturnValue());
    }
    params = params || {};
    fixParams = fixParams || {};
    if (jQuery.dialog && (params.showType == 'dialog' || !params.showType)) {
        var options = {
            Width: width,
            Height: height,
            Title: params.title || params.Title || fixParams.title || '',
            URL: url,
            dialogArguments: params,
            OnLoad: function () {
                var win = _dialog.innerFrame.contentWindow;
                win.parentWindow = window;
                win.dialogClose = win.close = function () {
                    innerCallback();
                    _dialog.close();
                };
                _dialogWin = win;
            }
        };
        options = $.extend({}, options, params, fixParams);
        var _dialog = jQuery.dialog(options).show();
        _dialog.closeAction = function () {
            innerCallback();
        }
        return _dialog;
    } else if (!$.browser.msie || params.showType == 'open') {

        if ($.block) { $.block({ timeout: 0 }); }
        _dialogArguments = params;
        var win = openCenterWindow(url, width, height);

        var _callbak = function () {
            if ($.unblock) { $.unblock(); }
            innerCallback();
        }

        if (jQuery.browser.msie) {
            win.attachEvent("onunload", _callbak);
        } else {
            win.onbeforeunload = _callbak;
        }
        _dialogWin = win;
        win.focus();
        return win;
    } else if ($.browser.msie) {
        _dialogWin = null;
        _returnValue = showCenterModalDialog(url, width, height, params);
        innerCallback();
    }
}

jQuery.dialogAraguments = function () {
    var args = window.dialogArguments;
    if (args) return args;
    var target = window.opener || window.parent;
    return target._dialogArguments;
}

jQuery.dialogReturnValue = function () {
    return _dialogWin ? _dialogWin.returnValue : _returnValue;
}


/*******************************************
@description 转化form表单元素为JSON对象（也可以为div）
@author  lixh@bingosoft.net
@example
var json = $(formSelector).toJson() ;
******************************************/
jQuery.fn.toJson = function (beforeExtend, afterExtend, params) {
    var me = jQuery(this);
    beforeExtend = beforeExtend || {};
    afterExtend = afterExtend || {};
    params = params || {};
    var a = {};

    //text hidden password
    me.find("input[type=text],input[type=hidden],input[type=password]").each(function () {
        _add(this.name || this.id, this.value);
    });
    me.find("textarea").each(function () {
        _add(this.name || this.id, this.value);
    });

    //radio
    me.find("input[type=radio]").filter(":checked").each(function () {
        _add(this.name || this.id, this.value);
    });

    //checkbox
    var temp_cb = "";
    me.find("input[type=checkbox]").filter(":checked").each(function () {
        if (temp_cb.indexOf(this.name) == -1) {
            temp_cb += (this.name) + ",";
        }
    });
    jQuery(temp_cb.split(",")).each(function () {
        var tempValue = [];
        jQuery("input[name='" + this + "']:checked").each(function (i) {
            tempValue.push(this.value);
        });
        _add(this, tempValue.join(","));
    });

    //select
    me.find('select').each(function () {
        var multi = $(this).attr('multiple');

        var val = [];
        jQuery(this).find('option[selected]').each(function () {
            if (this.value) val.push(this.value);
        });

        if (multi && params.mulSelectSplit) {
            _add(this.name || this.id, "'" + val.join("','") + "'");
        } else {
            _add(this.name || this.id, val.join(','));
        }
    });

    return $.extend(beforeExtend, a, afterExtend);

    function _add(key, value) {
        if (!key || !jQuery.trim(key)) return;

        value = value || '';
        a[key] = value;
    }
}

/**
* 格式化查询form
* 
* params
*/
jQuery.fn.formatQueryForm = function (params) {
    params = params || {};
    var exclude = params.exclude || '%&<>/';
    var gridId = params.gridId || null;
    var self = this;
    $(this).find('input[type=text],textarea').each(function () {
        if ($(this).excludeChar)
            $(this).excludeChar({ exclude: exclude });
        if (gridId) $(this).bind('keyup', function (event) {
            if (event.keyCode == 13) {
                gridId['queryForm'](self);
            }
        });
    });
}

/********************************************
**********添加文件指定窗口（JS、CSS）*********
********************************************/
jQuery.getTopWin = function () {
    var parentWin = window;
    while (parentWin != parentWin.parent) {
        try {
            if (parentWin.parent.document.getElementsByTagName("FRAMESET").length > 0) break;
            parentWin = parentWin.parent;
        } catch (e) {
            return parentWin;
        }

    }
    return parentWin;
}


jQuery.attachFile = function (win, filename, filetype) {
    if (win == window)
        return;
    if (!filename)
        return;
    var head = win.document.getElementsByTagName('head').item(0);
    var fileref = null;
    var fpath = null;
    if (filetype == "css") {
        if (_(win, 'link', filename))
            return; // 判断当前页面是否存在
        fpath = _(window, 'link', filename); // 获取路径
        if (!fpath)
            return;

        fileref = win.document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", fpath);
    } else if (filetype == "js") {

        if (_(win, 'script', filename))
            return;
        fpath = _(window, 'script', filename); // 获取路径
        if (!fpath)
            return;

        fileref = win.document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        fileref.setAttribute("language", "JavaScript");
        fileref.setAttribute("src", fpath);
    }

    head.appendChild(fileref);

    function _(win, tag, filename) {
        var scripts = win.document.getElementsByTagName(tag);
        for (var i = 0; i < scripts.length; i++) {
            var script = scripts[i];
            var _ = script.src || script.href;
            if (_ && _.indexOf("/" + filename) != -1) {
                return _ || '';
            }
        }
        return "";
    }
}

/********************************
*************jQuery.utils*******
*********************************/
jQuery.utils = {
    //解析URL
    parseUrl: function (url) {
        if (jQuery.trim(url).startWith("~")) {
            url = jQuery.trim(url).replace("~/", Global.contextPath + "/");
        }
        return url;
    },
    scrollContent: function (header, content, footer) {
        var header = content || ".header";
        var footbtn = footbtn || ".footbtn";
        var content = content || ".content";
        var contentHeight = $(document.body).height() - $(header).outerHeight() - $(footbtn).outerHeight() - 5;
        $(content).height(contentHeight).css({ 'overflow-x': 'hidden', 'overflow-y': 'auto' });
    }
};

jQuery.memory = {
    iframe: function (ifr, bool, b2) {
        ifr.src = "about:blank";

        var frames = ifr.contentWindow.document.getElementsByTagName("iframe");
        for (var i = 0; i < frames.length; i++) {
            jQuery.memory.iframe(frames[i], true);
        }

        ifr.contentWindow.document.write("");
        ifr.contentWindow.document.clear();

        if (!b2) {
            ifr.removeNode(true);
            ifr = null;
        }
        //if(!bool)CollectGarbage();
    }
}

jQuery.file = {
    /**
    * 文件下载
    *  eg: $.file.download("E:/bingo-celipse-jee-3.5.2_20100819.rar",realName) ;
    * @param {} filepath
    * @param {} filename
    */
    download: function (filepath, filename) {
        if (!filepath) {
            alert("下载文件不能为空！");
            return;
        }

        var url = jQuery.utils.parseUrl('~/download');

        if (!jQuery('#download_ifr')[0]) {
            jQuery(document.body).append("<iframe id=download_ifr name=download_ifr style='display:none;margin:0px;padding:0px;' src=''></iframe>");
        }

        if (!jQuery('#download_form')[0]) {
            jQuery(document.body).append("<form method=post id=download_form action='" + url + "' style='display:hide;margin:0px;padding:0px;' target=download_ifr>" +
					"<input type=hidden name=filepath id=__filepath value='" + (filepath || '') + "'>" +
					"<input type=hidden name=filename id=__filename value='" + (filename || '') + "'>" +
					"</form>");
        } else {
            jQuery('#__filepath').val(filepath || '');
            jQuery('#__filename').val(filename || '');
        }

        jQuery('#download_form').submit();
    },
    downloadCallback: function (flag, fileName) {
        if (flag == 1) {
            var msg = "文件[" + fileName + "]不存在或文件路径有误！";
            if ($.messageBox) {
                $.messageBox.error({ message: msg });
            } else {
                alert(msg);
            }
        }
    }
}

/**
* 统一获取数据入口
* 参数格式：
* 	1、 params
*       type: 'post',
url: 'demo-data.html' ,
data: req.term ,
async: true ,
dataType:'json'
         
返回数据格式
returnCode:       --  int
returnDesc:        -- string
error:                  --  string
returnValue:      --  json object
* 
*/

jQuery.request = function (params) {
    var _url = null;
    var _data = null;
    var _success = null;
    var _error = null;
    if (typeof params == 'string') {
        _url = params[0];
        _data = params[1];
        _success = params[2];
        _error = params[3];
        params = {};
    }

    if (jQuery.block && !params.noblock) jQuery.block();

    var dataType = params.dataType || 'text';
    var async = typeof params.async == 'undefined' ? true : params.async;
    var type = params.type || 'post';
    var error = params.error || _error || jQuery.request.defaultErrorHandler;
    var success = params.success || _success;
    var url = params.url || _url;
    var data = params.data || _data;

    if (jQuery.utils) url = jQuery.utils.parseUrl(url);
    $.ajax({
        type: type,
        url: url,
        data: data,
        async: async,
        dataType: dataType,
        success: function (response) {
            if (jQuery.unblock && !params.noblock) jQuery.unblock();
            var json = response;
            if (typeof (response) == 'string') {
                response = eval('json = ' + response);
            }

            if (typeof response.returnCode != 'undefined' && response.returnCode != 200) {
                error(null, response.returnCode, response.error, url);
            } else {
                if (!response.returnValue || typeof response.returnValue == 'string') {
                    if (response.returnValue == 0) {
                        success(0);
                    } else {
                        success(response.returnValue || response);
                    }
                }
                else {
                    success(response.returnValue.Rows || response.returnValue || response);
                }
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            if (jQuery.unblock && !params.noblock) jQuery.unblock();
            error(xhr, textStatus, errorThrown, url);
        }
    });
}

jQuery.request.defaultErrorHandler = function (xhr, textStatus, errorThrown, url) {
    alert('请求出现异常: ' + errorThrown + "\n\r[" + url + "]");
    //$.open(Global.contextPath + "/common/error/report500.jsp", 570, 410, errorThrown, null, { title: "提示信息" });
    return;
    /*if( $.messageBox ){
    $.messageBox.error({message:"ERROR:"+errorThrown}); 
    }else{
    alert('请求出现异常: ' + errorThrown+"\n\r["+url+"]" );
    }*/
}


/**
* 数据服务统一调用接口
* @param {} commandName
* @param {} params
* @param {} callback   {success:function(){},error:function(){}} or function(){}//success
*/
jQuery.dataservice = function (commandName, params, callback, reqParams) {
    callback = callback || {};
    params = params || {};
    params.CommandName = commandName;

    reqParams = reqParams || {};
    reqParams.data = params;
    reqParams.type = 'post';
    reqParams.noblock = reqParams.noblock === false ? false : true;
    reqParams.url = commandName ? "~/dataservice.ashx" : reqParams.url;
    reqParams.dataType = commandName ? 'json' : "text";

    //process callback
    if (callback.success) {
        reqParams.success = callback.success;
    }

    if (callback.error) {
        reqParams.error = callback.error;
    }

    if (jQuery.isFunction(callback)) {
        reqParams.success = callback;
    }

    jQuery.request(reqParams);
}

/*
* Title:  控件自动渲染
* Description:
* Aucthor: 陈锦城
* Email: chenjc@bingosoft.net
* Create Date:2010-07-19
* Copyright 2010
*/
$(function () {
    //获取UI控件的标识
    var ui_widget_class = ".widget-class";
    $(ui_widget_class).each(
	   function () {
	       var _options = $(this).attr('opts') || $(this).attr("options");

	       if (_options) {
	           _options = eval("(" + _options + ")");
	       } else {
	           _options = {};
	       }

	       if (typeof (widgetInitBefore) != 'undefined') {
	           widgetInitBefore($(this).attr("widget"));
	       }

	       var widgetInit = $(this).attr("widget") + "Init";
	       if ($[widgetInit]) $[widgetInit]($(this), _options);
	   }
	);
});

/*********************
* common 
* */
String.prototype.startWith = function (str) {
    var reg = new RegExp("^" + str);
    return reg.test(this);
}

String.prototype.endWith = function (str) {
    var reg = new RegExp(str + "$");
    return reg.test(this);
}
//获取url参数
$.queryString = function (key) {
    var str = window.location.search;
    var temp = null, result = "";
    $.each(str.substr(1).split("&"), function (index, val) {
        temp = val.split("=");
        if (temp.length == 2 && temp[0].toString().toLowerCase() == key.toString().toLowerCase()) {
            result = decodeURIComponent(temp[1]);
        }
    });
    return result;
};

//字符格式化实例方法
String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g, function (m, i) {
        return args[i];
    });
}

//向数组中添加格式化字符串
//[].pushFormat("{0},aaa{1}", "AA", "BB");
Array.prototype.pushFormat = function () {
    var args = arguments;
    var str = args[0].replace(/\{(\d+)\}/g, function (m, i) {
        return args[i * 1 + 1];
    });
    this.push(str);
}